import React, { Component } from 'react';
import styles from './SuperFormList.scss';
import { observable, action, computed } from 'mobx';
import { observer } from 'mobx-react';

import initView from '@/cross/components/View';
const View = initView(styles);
import initText from '@/cross/components/Text';
const Text = initText(styles);
import initImage from '@/cross/components/Image';
const Image = initImage(styles);
import initScrollView from '@/cross/components/ScrollView';
const ScrollView = initScrollView(styles);
import initImageBackground from '@/cross/components/ImageBackground';
const ImageBackground = initImageBackground(styles);

import { Page, HeaderBar, TabItem, Button, Modal, AutoList, ListItem } from '@/cross/components';
import DropDown from '@/cross/components/Picker/Dropdown';

import PutSuperForm from './PutSuperForm';

import { CrossPageProps } from '@/cross/pages/PropType';
import { Client } from '@/config';
import { px } from '@/cross/utils';
import { Article } from '@/types';
import { $service, $confirm, $message } from '@/cross/utils';
import tagStore from '@/cross/stores/tag';

interface IProps extends CrossPageProps {}

@observer
class PageView extends Component<IProps> {
  componentDidMount() {
    this.refresh();
    // 获取分类
    tagStore.fetchTagData(4);
  }

  putModalRef: Modal<PutSuperForm> | null = null;
  autoListRef: AutoList<Article> | null = null;
  @observable tab = 0;
  @action changeTab = (val: number) => {
    this.tab = val;
    this.refresh();
  };
  @computed get tagsTree() {
    return tagStore.allTagData[4] || [];
  }

  refresh = () => {
    this.autoListRef && this.autoListRef.refresh();
  };

  put = (item?: Article) => {
    this.putModalRef?.open({
      params: {
        item,
        onSave: () => {
          this.refresh();
        },
      },
    });
  };

  onItemAction = (action: 'edit' | 'remove' | 'more', item: Article) => {
    if (action === 'edit') {
      this.put(item);
    }
    if (action === 'remove') {
      $confirm('确认删除图文吗?')
        .then(() => {
          $service('rest', 'delete', {
            tableName: 'article',
            id: item._id,
          })
            .then(() => {
              $message.success('已删除');
              this.refresh();
            })
            .catch((e) => {
              if (e.errmsg) $message.error(e.errmsg);
            });
        })
        .catch(() => {});
    }
  };

  handleClickDropdown = (item: Article, index: number) => {
    this.onItemAction(index === 0 ? 'remove' : 'more', item);
  };

  fetchDate = (currentPage: number, pageSize?: number) => {
    return new Promise((resolve) => {
      let filterForm = {
        tag_id: this.tab ? this.tab : undefined,
      };
      let params = {
        tableName: 'article',
        currentPage,
        pageSize,
        count: false,
        filterForm,
      };
      $service('rest', 'get', params)
        .then(resolve)
        .catch((e) => {
          resolve([]);
        });
    });
  };

  renderItem = ({ item, index }: { item: Article; index: number }) => {
    return (
      <View key={index} className="M-p-h-b-15">
        <ListItem
          title={item.title}
          span={{
            left: [24, 24, 10],
            center: [12, 12, 8],
            right: [12, 12, 6],
          }}
          // avatar={require('../../assets/images/default_avatar.png')}
          center={
            <View className="M-vertical-middle M-p-l-5">
              <View>
                <Text className="M-f-s-12 M-f-c-666">阅读</Text>
                <View className="M-p-t-10" />
                <Text className="M-f-s-14 M-f-c-333">0</Text>
              </View>
              <View className="M-m-l-25">
                <Text className="M-f-s-12 M-f-c-666">点赞</Text>
                <View className="M-p-t-10" />
                <Text className="M-f-s-14 M-f-c-333">0</Text>
              </View>
              <View className="M-m-l-25">
                <Text className="M-f-s-12 M-f-c-666">分享</Text>
                <View className="M-p-t-10" />
                <Text className="M-f-s-14 M-f-c-333">0</Text>
              </View>
            </View>
          }
          right={
            <View className="M-horizontal-right">
              <View className="M-vertical-middle">
                <Button onClick={this.onItemAction.bind(this, 'edit', item)}>编辑</Button>
                <DropDown options={['删除']} onClick={this.handleClickDropdown.bind(this, item)}>
                  <Button className="M-m-l-10">更多</Button>
                </DropDown>
              </View>
            </View>
          }
        />
      </View>
    );
  };

  render() {
    return (
      <Page className="M-b-c-e chat-view">
        <HeaderBar
          title="超级表单"
          titleAlign="left"
          mode="light"
          leftContent={null}
          showBack={false}
          bottomContent={
            <View className="M-flexbox-horizontal M-p-t-5 M-p-l-10">
              <TabItem
                title="全部"
                active={this.tab === 0}
                onClick={this.changeTab.bind(this, 0)}
              />
              {this.tagsTree.map((tag) => {
                return (
                  <TabItem
                    key={tag.tag_id}
                    title={tag.tag_name || ''}
                    active={this.tab === tag.tag_id}
                    onClick={this.changeTab.bind(this, tag.tag_id || 0)}
                  />
                );
              })}
            </View>
          }
          rightContent={
            <View className="M-p-r-10">
              <Button color="primary" onClick={this.put.bind(this, undefined)}>
                新建表单
              </Button>
            </View>
          }
        />
        <AutoList<Article>
          onFetchData={this.fetchDate as any}
          renderHeader={<View className="M-p-t-5" />}
          renderItem={this.renderItem}
          gutter={[10, 10]}
          itemViewProps={{ col: true, md: 24, lg: 24, xl: 24, xxl: 12 }}
          ref={(node) => {
            this.autoListRef = node;
          }}
          emptyText="暂无表单"
        />
        {/* Modal */}
        <Modal<PutSuperForm>
          ref={(node) => (this.putModalRef = node)}
          zIndex={10}
          width={Client === 'worktop' ? px(750) : px(750)}
          height={Client === 'worktop' ? 'calc(60vh)' : undefined}
          renderView={(props) => <PutSuperForm {...props} />}
        />
      </Page>
    );
  }
}

export default PageView;
